package com.block.im.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.util.LocalDateUtil;
import com.block.db.entity.ImUserSigInfo;
import com.block.im.config.IMConfig;
import com.block.im.enums.IMUriEnum;
import com.block.im.enums.StatusEnum;
import com.block.im.enums.UserTypeEnum;
import com.block.im.model.dto.IMHttpResultDTO;
import com.block.im.model.param.ImUserParam;
import com.block.im.service.IImBaseCommonService;
import com.block.im.service.IImUserSigInfoService;
import com.block.im.util.ImHttpUtil;
import com.block.im.util.ImUserUtil;
import com.tencentyun.TLSSigAPIv2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ImBaseCommonServiceImpl implements IImBaseCommonService {

    @Autowired
    IImUserSigInfoService imUserSigInfoService;
    @Autowired
    IMConfig imConfig;
    @Autowired
    ImHttpUtil imHttpUtil;

    @Override
    public ImUserSigInfo genUserSig(String userId){

        Long sdkExpire = imConfig.getSdkExpire();
        // 超时时间设置为 提前一个小时
        LocalDateTime expireTime = LocalDateTime.now().plusSeconds(sdkExpire - (60*60));

        TLSSigAPIv2 tlsSigAPIv2 = new TLSSigAPIv2(Long.valueOf(imConfig.getSdkAppId()), imConfig.getSdkKey());
        String userSig = tlsSigAPIv2.genUserSig(userId, imConfig.getSdkExpire());

        ImUserSigInfo imUserSigInfo = new ImUserSigInfo();
        imUserSigInfo.setDateInfo(LocalDate.now().toString());
        imUserSigInfo.setUserId(userId);
        imUserSigInfo.setUserSig(userSig);
        imUserSigInfo.setExpireTime(LocalDateUtil.getDateFormatStr(expireTime, LocalDateUtil.TOTAL_DATE_TIME));
        imUserSigInfo.setStatus(StatusEnum.EFFECT.getValue());

        return imUserSigInfo;
    }


    /**
     * 导入账号
     * @param accountList
     * @return
     */
    @Override
    public IMHttpResultDTO accountImport(List<ImUserParam> accountList){

        String uri = IMUriEnum.ACCOUNT_IMPORT.getValue();

        JSONArray AccountList = new JSONArray();
        for (ImUserParam imUserParam : accountList) {

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("UserID", imUserParam.getUserId());
            jsonObject.put("Nick", imUserParam.getNickname());
            jsonObject.put("FaceUrl", imUserParam.getHeadImage());

            AccountList.add(jsonObject);
        }

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("AccountList", AccountList);

        IMHttpResultDTO imHttpResultDTO = imHttpUtil.httpRequest(uri, paramMap);
        if (imHttpResultDTO.isSuccess()){
            JSONObject resultObj = imHttpResultDTO.getResultObj();
            JSONArray failAccounts = resultObj.getJSONArray("FailAccounts");
            if (failAccounts.size()>0){
                imHttpResultDTO.setSuccess(false);
                imHttpResultDTO.setFailedImportAccountList(JSON.parseArray(JSON.toJSONString(failAccounts), String.class));
            }
        }
        return imHttpResultDTO;
    }

    /**
     * 发送单聊信息
     * https://cloud.tencent.com/document/product/269/2282
     *
     */
    @Override
    public IMHttpResultDTO sendSystemMsgInfo(ImUserParam toUser, String msgContent){
        ImUserParam fromUser = new ImUserParam("001", UserTypeEnum.SYS);
        return  this.sendSingleMsgInfo(fromUser, toUser, msgContent);
    }

    @Override
    public IMHttpResultDTO sendSingleMsgInfo(ImUserParam fromUser, ImUserParam toUser, String msgContent){

        String uri = IMUriEnum.SEND_MSG.getValue();

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("From_Account", fromUser.getUserId());
        paramMap.put("To_Account", toUser.getUserId());
        paramMap.put("MsgRandom", RandomUtil.randomInt(Integer.MAX_VALUE));

        JSONObject msgItem = new JSONObject();
        msgItem.put("MsgType", "TIMTextElem");

        JSONObject MsgContent = new JSONObject();
        MsgContent.put("Text", msgContent);
        msgItem.put("MsgContent", MsgContent);

        JSONArray MsgBody = new JSONArray();
        MsgBody.add(msgItem);

        paramMap.put("MsgBody", MsgBody);

        System.out.println();
        System.out.println(JSON.toJSONString(paramMap));
        System.out.println();
        IMHttpResultDTO imHttpResultDTO = imHttpUtil.httpRequest(uri, paramMap);

        return imHttpResultDTO;
    }


    /**
     * 拉取会话列表
     * @return
     */
    @Override
    public IMHttpResultDTO getSessionList(ImUserParam fromUser, Integer startIndex){

        /**
         * From_Account  String  必填  填 UserID，请求拉取该用户的会话列表。
         * TimeStamp  Integer  必填  普通会话的起始时间，第一页填 0。
         * StartIndex Integer 必填  普通会话的起始位置，第一页填 0。
         * TopTimeStamp  Integer  必填  置顶会话的起始时间，第一页填 0。
         * TopStartIndex  Integer  必填  置顶会话的起始位置，第一页填 0。
         * AssistFlags  Integer  必填  会话辅助标志位：填固定值 15。
         */
        String uri = IMUriEnum.SESSION_LIST.getValue();

        String From_Account = fromUser.getUserId();

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("From_Account", From_Account);
        paramMap.put("TimeStamp", 0);
        paramMap.put("StartIndex", startIndex);
        paramMap.put("TopTimeStamp", 0);
        paramMap.put("TopStartIndex", 0);
        paramMap.put("AssistFlags", 15);

        IMHttpResultDTO imHttpResultDTO = imHttpUtil.httpRequest(uri, paramMap);

        return imHttpResultDTO;
    }


    /**
     * 拉取单聊历史信息
     * @return
     */
    @Override
    public IMHttpResultDTO getHistoryMsg(ImUserParam mainUser, ImUserParam peerUser, String lastMsgKey){

        /**
         * Operator_Account String 必填 会话其中一方的 UserID，以该 UserID 的角度去查询消息。同一个会话，分别以会话双方的角度去查询消息，结果可能会不一样，请参考本接口的接口说明
         * Peer_Account String 必填 会话的另一方 UserID
         * MaxCnt Integer 必填 请求的消息条数
         * MinTime Integer 必填 请求的消息时间范围的最小值（单位：秒）
         * MaxTime Integer 必填 请求的消息时间范围的最大值（单位：秒）
         * LastMsgKey String 选填 上一次拉取到的最后一条消息的 MsgKey，续拉时需要填该字段，填写方法见上方 示例
         */
        String uri = IMUriEnum.MSG_HISTORY.getValue();

        String Operator_Account = mainUser.getUserId();
        String Peer_Account = peerUser.getUserId();

        LocalDateTime startTime = LocalDateUtil.getDateTimeByStr("2024-09-01 00:00:00", LocalDateUtil.TOTAL_DATE_TIME);
        LocalDateTime endTime = LocalDateUtil.getDateTimeByStr("2025-09-01 00:00:00", LocalDateUtil.TOTAL_DATE_TIME);

        Long minTime = LocalDateUtil.getTimeSeconds(startTime);
        Long maxTime = LocalDateUtil.getTimeSeconds(endTime);

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("Operator_Account", Operator_Account);
        paramMap.put("Peer_Account", Peer_Account);
        paramMap.put("MaxCnt", 50);
        paramMap.put("MinTime", minTime);
        paramMap.put("MaxTime", maxTime);
        if (ObjectUtil.isNotEmpty(lastMsgKey)){
            paramMap.put("LastMsgKey", lastMsgKey);
        }

        IMHttpResultDTO imHttpResultDTO = imHttpUtil.httpRequest(uri, paramMap);

        return imHttpResultDTO;
    }
}

